package com.uetoken.cn.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.FundAssetDetailsAdapter;
import com.uetoken.cn.adapter.holder.AbnormalViewHolder;
import com.uetoken.cn.adapter.model.FundAssetDetailsModel;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ChargeCNVHisBean;
import com.uetoken.cn.bean.PurseListHisBean;
import com.uetoken.cn.bean.StockOutHistoryBean;
import com.uetoken.cn.bean.SubPurseHistoryBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

public class HistoryActivity extends BaseActivity implements WebResponse, Handler.Callback, AbnormalViewHolder.OnRegainClickListener {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    //    @BindView(R.id.abnormalLayout)
//    FrameLayout mAbnormalLayout;
    @BindView(R.id.details1)
    TextView mDetails1;
    @BindView(R.id.details2)
    TextView mDetails2;

    /**
     * 获取钱包更多历史网络请求码 more
     */
    private static final int NETWORK_REQUEST_PURSE_MORE_LIST_HIS = 11;
    /**
     * 子钱包id
     */
    private String purseId;
    /**
     * recyclerview要显示的数据
     */
    private List<FundAssetDetailsModel> mFundList;
    /**
     * 数据获取错误下的view
     */
    private View abnormalView;
    /**
     * 判断是否有网络
     */
    private boolean noNetwork = false;
    /**
     * 判断是否有网络
     */
    private boolean isAbnormal = false;
    /**
     * 判断是否是子钱包
     */
    private int historyType = 0;
    private String nodeid;

    private Handler mHandler;
    private FundAssetDetailsAdapter mFundAssetDetailsAdapter;
    private Unbinder unbinder;
    private int pursetypeid;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recent_transaction_records;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        unbinder = ButterKnife.bind(this);
        mHandler = new Handler(this);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        purseId = intent.getStringExtra("purseId");
        historyType = intent.getIntExtra("historyType", 0);
        pursetypeid = intent.getIntExtra("pursetypeid", -1);
        nodeid = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        getData();
        initTopBar();
        if (historyType == Constant.MIAN_PURSE_HIS) {
            mDetails1.setText(getResources().getString(R.string.str_recent_transaction_records));
            mDetails2.setVisibility(View.GONE);
            mTopbar.setTitle(R.string.recently_transaction_record);
        } else if (historyType == Constant.CHILD_PURSE_HIS) {
            mDetails1.setText(getResources().getString(R.string.str_transaction_record));
            mDetails2.setVisibility(View.VISIBLE);
            mDetails2.setText(getResources().getString(R.string.money_txt));
            mTopbar.setTitle(R.string.str_child_purse_detail);
        } else if (historyType == Constant.STOCK_OUT_HIS) {
            mDetails1.setText(getResources().getString(R.string.str_transaction_record));
            mDetails2.setVisibility(View.VISIBLE);
            mDetails2.setText(getResources().getString(R.string.money_txt));
            mTopbar.setTitle(R.string.str_stockout_history);
        } else if (historyType == Constant.CHARGE_CNV_HIS) {
            mDetails1.setText(getResources().getString(R.string.str_recent_transaction_records));
            mDetails2.setVisibility(View.GONE);
            mTopbar.setTitle(R.string.str_recently_exchange_record);
        } else {
            mDetails1.setText(getResources().getString(R.string.str_recent_transaction_records));
            mDetails2.setVisibility(View.GONE);
            mTopbar.setTitle(R.string.recently_transaction_record);
        }
        initRecyclerView();
    }

    @Override
    public void init() {

    }

    private void getData() {
        showLoading();
        Map<String, String> newMap;
        if (historyType == Constant.CHARGE_CNV_HIS) {
            newMap = Params.getChargeCNVListHistoryParams(nodeid, "1", "999");
        } else {
            newMap = Params.getPurseListHistoryParams(purseId, "30", "0", historyType);
        }
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseListHistoryUrl(historyType), NETWORK_REQUEST_PURSE_MORE_LIST_HIS,
                newMap);
    }

    private void initTopBar() {
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void initRecyclerView() {
        mFundList = new ArrayList<>();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mRecyclerView.addItemDecoration(new SimpleDividerDecoration(this));
        mFundAssetDetailsAdapter = new FundAssetDetailsAdapter(R.layout.fund_asset_item, mFundList);
        mRecyclerView.setVisibility(View.VISIBLE);
        mRecyclerView.setAdapter(mFundAssetDetailsAdapter);
    }

    private void initAbnormalLayout(boolean noNetwork) {
        AbnormalViewHolder mAbnormalViewHolder;
//        if (!isAbnormal) {
//            isAbnormal = true;
//            abnormalView = LayoutInflater.from(this).inflate(R.layout.view_abnormal, null, false);
//            mAbnormalLayout.addView(abnormalView);
////            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mAbnormalLayout.getLayoutParams();
////            params.height
//            mAbnormalViewHolder = new AbnormalViewHolder(abnormalView);
//            mAbnormalLayout.setTag(mAbnormalViewHolder);
//        } else {
//            mAbnormalViewHolder = (AbnormalViewHolder) mAbnormalLayout.getTag();
//        }
        abnormalView = LayoutInflater.from(this).inflate(R.layout.view_abnormal, null, false);

        mFundAssetDetailsAdapter.setEmptyView(abnormalView);
        mAbnormalViewHolder = new AbnormalViewHolder(abnormalView);
        mAbnormalViewHolder.setOnRegainClickListener(this);
        if (noNetwork) {
            mAbnormalViewHolder.mAbnormalIv.setImageResource(R.drawable.ic_no_network);
            mAbnormalViewHolder.mAbnormalTv.setText(R.string.str_abnormal_nonetwork_explain);
        } else {
            mAbnormalViewHolder.mAbnormalIv.setImageResource(R.drawable.ic_no_data);
            mAbnormalViewHolder.mAbnormalTv.setText(R.string.str_abnormal_nocontent_explain);
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("HistoryActivity==", "HistoryActivity== onSuccessResponse response = " + response);
        dissmissDialog();
        if (requestCode == NETWORK_REQUEST_PURSE_MORE_LIST_HIS) {
            try {
                PurseListHisBean purseListHisBean;
                SubPurseHistoryBean subPurseHistoryBean;
                StockOutHistoryBean stockOutHistoryBean;
                ChargeCNVHisBean chargeCNVHisBean;

                int result = 0;
                String msg = "";
                List<?> list = null;
                if (historyType == Constant.MIAN_PURSE_HIS || historyType == Constant.CHILD_PURSE_HIS) {
                    purseListHisBean = new Gson().fromJson(response, PurseListHisBean.class);
                    result = purseListHisBean.getResult();
                    msg = purseListHisBean.getMessage();
                    list = purseListHisBean.getData().getPursehis();
                }
//                else if (historyType == Constant.CHILD_PURSE_HIS) {
//                    subPurseHistoryBean = new Gson().fromJson(response, SubPurseHistoryBean.class);
//                    result = subPurseHistoryBean.getResult();
//                    msg = subPurseHistoryBean.getMessage();
//                    list = subPurseHistoryBean.getData();
//                }
                else if (historyType == Constant.STOCK_OUT_HIS) {
                    stockOutHistoryBean = new Gson().fromJson(response, StockOutHistoryBean.class);
                    result = stockOutHistoryBean.getResult();
                    msg = stockOutHistoryBean.getMessage();
                    list = stockOutHistoryBean.getData();
                } else if (historyType == Constant.CHARGE_CNV_HIS) {
                    chargeCNVHisBean = new Gson().fromJson(response, ChargeCNVHisBean.class);
                    result = chargeCNVHisBean.getResult();
                    msg = chargeCNVHisBean.getMessage();
                    list = chargeCNVHisBean.getData();
                }

                if (result > 0) {
                    Message message = new Message();
                    message.obj = list;
                    message.what = Constant.HANDLER_MESSAGE_WHAT_1100;
                    mHandler.sendMessage(message);
                } else {
                    ToastUtils.showShort(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Message message = new Message();
                message.what = Constant.HANDLER_MESSAGE_WHAT_1101;
                mHandler.sendMessage(message);
            }
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        Message message = new Message();
        message.what = Constant.HANDLER_MESSAGE_WHAT_1101;
        mHandler.sendMessage(message);
    }

    /**
     * 刷新recyclerview数据
     *
     * @param pursehis
     */
    private void refreshRecyclerview(List<?> pursehis) {
        for (int i = 0; i < pursehis.size(); i++) {
            FundAssetDetailsModel mFundAssetDetailsModel = new FundAssetDetailsModel();
            PurseListHisBean.DataBean.PursehisBean pursehisBean;
            SubPurseHistoryBean.DataBean subPurseHis;
            StockOutHistoryBean.DataBean stockOutHis;
            ChargeCNVHisBean.DataBean chargeCNVHis;
            String remarks = "";
            String amount;
            String createtime;
            int typeid = -1;
            String symbol = "";
            String balanceformat = "";
            String balanceafterformat = "";
            String balanceafter = "";
            boolean isShowBalance;
            if (historyType == Constant.MIAN_PURSE_HIS || historyType == Constant.CHILD_PURSE_HIS) {
                pursehisBean = (PurseListHisBean.DataBean.PursehisBean) pursehis.get(i);
                remarks = pursehisBean.getRemarks();
                typeid = pursehisBean.getTypeid();
                createtime = pursehisBean.getCreatetime();
                amount = pursehisBean.getBalance();
                balanceformat = pursehisBean.getBalanceformat();
                balanceafter = pursehisBean.getBalanceafter();
                balanceafterformat = pursehisBean.getBalanceafterformat();
                if (pursetypeid == 3) {
                    amount = balanceformat;
                    balanceafter = balanceafterformat;
                }
                isShowBalance = true;
            } else if (historyType == Constant.STOCK_OUT_HIS) {
                stockOutHis = (StockOutHistoryBean.DataBean) pursehis.get(i);
                remarks = stockOutHis.getRemarks();
                typeid = -1;
                amount = stockOutHis.getAmount().doubleValue() + "";
                createtime = stockOutHis.getCreatetime();
                isShowBalance = false;
            } else if (historyType == Constant.CHARGE_CNV_HIS) {
                chargeCNVHis = (ChargeCNVHisBean.DataBean) pursehis.get(i);
                amount = chargeCNVHis.getAmount().doubleValue() + "";
                typeid = chargeCNVHis.getTransid();
                createtime = chargeCNVHis.getCreatetime();
                remarks = chargeCNVHis.getRemarks();
                isShowBalance = false;
            } else {
                pursehisBean = (PurseListHisBean.DataBean.PursehisBean) pursehis.get(i);
                remarks = pursehisBean.getRemarks();
                typeid = pursehisBean.getTypeid();
                amount = pursehisBean.getBalance();
                createtime = pursehisBean.getCreatetime();
                balanceformat = pursehisBean.getBalanceformat();
                balanceafterformat = pursehisBean.getBalanceafterformat();
                isShowBalance = true;
                balanceafter = pursehisBean.getBalanceafter();
                if (pursetypeid == 3) {
                    amount = balanceformat;
                    balanceafter = balanceafterformat;
                }
            }

            mFundAssetDetailsModel.setWithdrawDeposit(remarks);
            mFundAssetDetailsModel.setTypeid(typeid);
            mFundAssetDetailsModel.setTimeWithdraw(createtime);
            mFundAssetDetailsModel.setMoney(amount);
            mFundAssetDetailsModel.setBalanceafter(balanceafter);
            mFundAssetDetailsModel.setIsShowBalance(isShowBalance);
            mFundList.add(mFundAssetDetailsModel);
        }
        mFundAssetDetailsAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constant.HANDLER_MESSAGE_WHAT_1100:
                List<?> pursehis = (List<?>) msg.obj;
                if (pursehis == null) {
//                    mAbnormalLayout.setVisibility(View.VISIBLE);
//                    mRecyclerView.setVisibility(View.GONE);
                    noNetwork = false;
                    initAbnormalLayout(noNetwork);
                } else {
                    if (pursehis.size() <= 0) {
//                        mAbnormalLayout.setVisibility(View.VISIBLE);
//                        mRecyclerView.setVisibility(View.GONE);
                        noNetwork = false;
                        initAbnormalLayout(noNetwork);
                    } else {
//                        mAbnormalLayout.setVisibility(View.GONE);
//                        mRecyclerView.setVisibility(View.VISIBLE);
                        refreshRecyclerview(pursehis);
                    }
                }
                break;
            case Constant.HANDLER_MESSAGE_WHAT_1101:
                dissmissDialog();
                noNetwork = true;
//                mAbnormalLayout.setVisibility(View.VISIBLE);
//                mRecyclerView.setVisibility(View.GONE);
                initAbnormalLayout(noNetwork);
                break;
        }
        return false;
    }

    @Override
    public void onRegainData(View view) {
        if (noNetwork) {
            getData();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class SimpleDividerDecoration extends RecyclerView.ItemDecoration {

        private int dividerHeight;
        private Paint dividerPaint;

        public SimpleDividerDecoration(Context context) {
            dividerPaint = new Paint();
            dividerPaint.setColor(context.getResources().getColor(R.color.app_color_common_gray));
            dividerHeight = context.getResources().getDimensionPixelSize(R.dimen.spacing_05dp);
        }


        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = dividerHeight;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getChildCount();
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();

            for (int i = 0; i < childCount - 1; i++) {
                View view = parent.getChildAt(i);
                float top = view.getBottom();
                float bottom = view.getBottom() + dividerHeight;
                c.drawRect(left, top, right, bottom, dividerPaint);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        unbinder.unbind();
    }
}
